package com.sense.ioc;

import com.sense.ioc.bean.BeanDefinition;
import com.sense.ioc.bean.ReferenceDefinition;
import com.sense.ioc.register.IBeanRegister;
import com.sense.ioc.register.IocRegister;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Creator: LanJian (lanjian860217@gmail.com)
 * Date: 2/1/11
 * Time: 3:18 PM
 */
public class IocWorker extends IocRegister {
    private static boolean load = false;
    private static IocWorker iocWorker = null;
    private IBeanRegister[] beanRegisters;

    private IocWorker() {

    }

    public synchronized static IocWorker newInstance() {
        if (!load && iocWorker == null) {
            iocWorker = new IocWorker();
            iocWorker.init();
            load = true;
        }
        return iocWorker;
    }

    public void setBeanRegisters(IBeanRegister[] beanRegisters) {
        this.beanRegisters = beanRegisters;
    }


    private void init() {
        try {
            registerBeans();
            loadReferences();
            loadInitMethod();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }


    private void registerBeans() {
        for (IBeanRegister beanRegister : beanRegisters) {
            initRegister(beanRegister);
        }
    }

    private void loadReferences() throws IllegalAccessException, InstantiationException {
        Set keySet = beanDefinitions.keySet();
        Iterator keyIterators = keySet.iterator();
        while (keyIterators.hasNext()) {
            BeanDefinition beanDefinition = beanDefinitions.get(keyIterators.next());
            beanDefinition.fixReferences();
        }
    }

    public void loadInitMethod() {

    }

    private void initRegister(IBeanRegister beanRegister) {
        if (beanRegister instanceof IBeanRegister) {
            beanRegister.register();
        } else {
            throw new RuntimeException("bean register error! please check you IBeanRegister impl");
        }
    }
}
